#include "../../logs/log.h"
#include "../epoll_server/Socket.hpp"
#include "logmsg.pb.h"
#include "Protocol.hpp"
#include <random>
#include <unistd.h>

class OtherHostSink : public logs::LogSink
{
public:
    OtherHostSink(const std::string &ip, int port) : _cli(std::make_unique<Net_Work::TcpSocket>())
    {
        _cli->BuildConnectSocketMethod(ip, port);
        _host_id = generate_hex(5);
    }
    void log(const char *data, size_t len)
    {
        // 添加序列化
        // 构建序列化消息对象
        log_msg::LogRequest req;
        std::string s(data, len);
        req.set_msg(s);
        req.set_hostid(_host_id);
        // 序列化
        std::string msg;
        if (!req.SerializeToString(&msg))
        {
            std::cerr << "序列化失败" << std::endl;
            return;
        }
        std::string req_str = Protocol::Encode(msg);
        // 通过网络发送
        std::cout << req_str << std::endl;
        int sock_fd = _cli->GetSockFd();
        write(sock_fd, req_str.c_str(), req_str.size());
    }

private:
    unsigned int random_char()
    {
        // ⽤于随机数引擎获得随机种⼦
        std::random_device rd;
        // mt19937是c++11新特性，它是⼀种随机数算法，⽤法与rand()函数类似，但是mt19937具有速度快，周期⻓的特点
        // ⽣成伪随机数
        std::mt19937 gen(rd());
        // 随机⽣成⼀个整数i 范围[0, 255]
        std::uniform_int_distribution<> dis(0, 255);
        return dis(gen);
    }
    // ⽣成 UUID （通⽤唯⼀标识符）
    std::string generate_hex(const unsigned int len)
    {
        std::stringstream ss;
        // ⽣成 len 个16进制随机数，将其拼接⽽成
        for (auto i = 0; i < len; i++)
        {
            const auto rc = random_char();
            std::stringstream hexstream;
            hexstream << std::hex << rc;
            auto hex = hexstream.str();
            ss << (hex.length() < 2 ? '0' + hex : hex);
        }
        return ss.str();
    }

private:
    std::unique_ptr<Net_Work::Socket> _cli;
    std::string _host_id;
};

void test_log()
{
    DEBUG("%s", "测试开始！");

    // logs::logger::ptr logger = logs::LoggerManager::getInstance().get_Logger("async_logger");
    logs::logger::ptr logger = logs::getLogger("async_logger");
    logger->debug("%s", "异步日志器测试...");
    logger->info("%s", "异步日志器测试...");
    logger->warn("%s", "异步日志器测试...");
    logger->error("%s", "异步日志器测试...");
    logger->fatal("%s", "异步日志器测试...");
    size_t cnt = 0;
    while (cnt < 10000)
    {
        logger->fatal("%s - %d", "异步日志器测试...", cnt++);
        usleep(1000);
    }

    DEBUG("%s", "测试结束！");
}
int main()
{
    // 可自定义创建日志器，定义日志器的输出
    std::unique_ptr<logs::LoggerBuilder> builder = std::make_unique<logs::GlobalLoggerBuild>();
    builder->BuilderLoggerType(logs::LoggerType::LOGGER_ASYNC);
    builder->BuilderLoggerName("async_logger");
    builder->BuilderLoggerLevel(logs::LogLevel::Value::WARN);
    // builder->BuilderLoggerFormatter("%m%n");
    // builder->buildSink<logs::StdoutSink>();
    // builder->buildSink<RollByTimeSink>("./aa/test-", TimeGap::GAP_SECOND);
    // builder->BuilderEnableUnsafeAsync();

    builder->buildSink<OtherHostSink>("127.0.0.1", 8888);
    builder->build();

    logs::logger::ptr logger = logs::getLogger("async_logger");
    int cnt = 3;
    while (cnt--)
    {
        logger->fatal("%s", "异步日志器测试...");
        sleep(1);
    }

    // test_log();
    return 0;
}